<?php

namespace App\Http\Controllers\V1\Api;

use App\Http\Requests\Api\OpinionServer;
use App\Models\V1\Community;

use App\Models\V1\Opinion;
use App\Models\V1\OpinionClass;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class OpinionController extends BaseController
{

    /**
     * 用户发表意见
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function Add(OpinionServer $request)
    {
        $request->validate('v1.create');
        $user = auth('box')->user();

        $title = $request->input('title');
        $opinion_class_id = $request->input('opinion_class_id');
        $describe = $request->input('describe');
        $thumb = $request->input('thumb');


        $community_name = Community::where('id', $user['community_id'])->value('name');
        $opinion_class_name = OpinionClass::where('id', $opinion_class_id)->value('title');

        $model = new Opinion();
        try {
            DB::beginTransaction();
            $model->create([
                'opinion_class_id' => $opinion_class_id,
                'title' => $title,
                'describe' => $describe,
                'thumb' => $thumb,
                'mobile' => $user['mobile'],
                'user_id' => $user['id'],
                'username' => $user['username'],
                'community_id' => $user['community_id'],
                'community_name' => $community_name,
                'opinion_class_name' => $opinion_class_name,
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ajax_output(300, "数据异常:" . $e->getMessage());
        }
        return ajax_output(200, "成功");
    }


}
